const {src, dest, series, parallel} = require('gulp')
const revCollector = require('gulp-rev-collector')
const rev = require('gulp-rev')
const path = require('path')

const webpackStream = require('webpack-stream')
const gulpSass = require('gulp-sass')
const cleanCSS = require('gulp-clean-css')

//打包HTML
function copyhtml(){
    return src('./*.html')
        .pipe(dest('./dist'))
}

//打包img
function copyimages(){
    return src('./src/images/**/*')
        .pipe(dest('./dist/images'))
}

//打包libs
function copylibs(){
    return src('./src/libs/**/*')
        .pipe(dest('./dist/libs'))
}

//打包iconsy
function copyicons(){
    return src('./src/icons/**/*')
        .pipe(dest('./dist/icons'))
}

//打包JS并把ES678编译成ES5
function packjs(){
    return src('./src/**/*')
    .pipe(webpackStream({
        mode: 'production',

        entry: {
            app: './src/app.js'
        },

        output: {
            filename: '[name].js',
            path: path.resolve(__dirname, './dist')
        },

        // 将ES6-ES8 代码转换成 ES5
        module: {
            rules: [
                {
                    test: /\.m?js$/,
                    exclude: /(node_modules|bower_components)/,
                    use: {
                        loader: 'babel-loader',
                        options: {
                            presets: ['@babel/preset-env'],
                            plugins: ['@babel/plugin-transform-runtime']
                        }
                    }
                },
                {
                    test: /\.html$/,
                    loader: 'string-loader'
                }
            ]
        }
    }))
    .pipe(rev())//添加hash后缀
    .pipe(dest('./dist/scripts'))
    .pipe(rev.manifest())//生成文件映射
    .pipe(dest('./rev/scripts'))//将映射文件导出到rev/css
}

//打包SASS并编译成CSS
function packCss(){
    return src('./src/styles/*.scss')
        .pipe(rev())//添加hash后缀
        .pipe(gulpSass().on('error', gulpSass.logError))
        .pipe(cleanCSS({compatibility: 'ie8'}))
        .pipe(dest('./dist/styles/'))
        .pipe(rev.manifest())//生成文件映射
        .pipe(dest('./rev/styles'))//将映射文件导出到rev/css
}

function revColl(){
    return src(['./rev/**/*.json', 'dist/*.html'])
        .pipe(revCollector())
        .pipe(dest('./dist'));
}



exports.default = series(parallel(packjs, packCss, copyimages, copyicons, copylibs), copyhtml, revColl)
